import { RouteRecordRaw, RouteMeta } from 'vue-router'

interface CustomRouteMeta extends RouteMeta {
  title?: string
  hidden: boolean
  redirect?: string
}

interface PreprocessedPage {
  originalPath: string // 原始page.ts文件路径
  routePath: string // 转换后的路由路径
  componentPath: string // 组件路径
  meta: CustomRouteMeta // 路由元信息
  depth: number // 路径深度
}

const pages: Record<string, CustomRouteMeta> = import.meta.glob('../../views/**/page.ts', {
  eager: true,
  import: 'default' // 拿到默认导出的内容
}) // Object[{ '../../views/**/page.ts': meta }]
const components = import.meta.glob('../../views/**/Index.vue', { eager: true, import: 'default' })

// 预处理所有页面的路径，避免重复计算
const preprocessedPages: PreprocessedPage[] = Object.entries(pages).map(([path, meta]) => {
  const routePath = path.replace('../../views', '').replace('/page.ts', '').toLowerCase() || '/'
  const componentPath = path.replace('/page.ts', '/Index.vue')
  const depth = routePath.split('/').filter(Boolean).length // 路由层数

  return { originalPath: path, routePath, componentPath, meta, depth }
})

// 构建路径前缀树，提高查找效率
const buildPathTree = (preprocessedPages: PreprocessedPage[]) => {
  if (!preprocessedPages || !preprocessedPages.length) return {}
  const tree: Record<string, PreprocessedPage[]> = {}

  preprocessedPages.forEach((page) => {
    const segments = page.routePath.split('/').filter(Boolean) // ['login'], ['home', 'home1']
    let currentPath = ''

    segments.forEach((segment) => {
      currentPath = currentPath ? `${currentPath}/${segment}` : `/${segment}`
      if (!tree[currentPath]) {
        tree[currentPath] = []
      }
      tree[currentPath].push(page)
    })
  })

  return tree
}

const pathTree = buildPathTree(preprocessedPages)

// 递归生成路由
const generateRoute = (targetPath: string, currentDepth: number): RouteRecordRaw[] => {
  if (!pathTree || !Object.keys(pathTree).length) return []
  const childrenPages =
    pathTree[targetPath]?.filter(
      (page) =>
        page.routePath.startsWith(targetPath) &&
        page.routePath !== targetPath &&
        page.depth === currentDepth + 1
    ) || []

  if (childrenPages.length === 0) {
    return []
  }

  return childrenPages
    .map((page) => {
      const routeName = page.routePath.split('/').filter(Boolean).join('-') || 'index'

      return {
        path: page.routePath,
        name: routeName,
        component: components[page.componentPath],
        meta: page.meta,
        children: generateRoute(page.routePath, currentDepth + 1),
        redirect: page.meta.redirect
      } as RouteRecordRaw
    })
    .filter((route) => Object.keys(route).length > 0)
}

// 生成根级路由
const autoInitRoutes = preprocessedPages
  .filter((page) => page.depth === 1) // 只处理第一级路由
  .map((page) => {
    const routeName = page.routePath.split('/').filter(Boolean).join('-') || 'index'

    return {
      path: page.routePath,
      name: routeName,
      component: components[page.componentPath],
      meta: page.meta,
      children: generateRoute(page.routePath, 1),
      redirect: page.meta.redirect
    } as RouteRecordRaw
  })
  .filter((route) => Object.keys(route).length > 0)

const remainingRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('@/layout/Index.vue'),
    name: 'layout',
    meta: { hidden: false },
    redirect: autoInitRoutes.length ? '/home' : undefined,
    children: [
      ...autoInitRoutes.filter((item) => item.path !== '/login'),
      {
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        name: 'any',
        meta: { title: '任意路由', hidden: true }
      }
    ]
  }
]

export default remainingRoutes
